package com.dykj.fireFighting.web.controller;

import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.base.video.service.IVideoLocalService;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DownLoadFileUtils;
import com.dykj.fireFighting.web.mongodb.GridFSRepository;
import com.dykj.fireFighting.api.base.file.service.DataFilesService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@RestController
@RequestMapping("/file")
public class FileController {


    @Value("${file.upload-folder}")
    private String uploadFolder;
    @Value("${file.access-prefix-url}")
    private String accessPrefixUrl;
    @DubboReference
    private DataFilesService iDataFilesService;
    @Autowired
    private GridFSRepository gridFSRepository;
    @DubboReference
    private IVideoLocalService videoLocalService;

    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件")
    public CommonResult upload(MultipartFile file) throws Exception {
        String id = iDataFilesService.uploadFile(file);
        return CommonResult.success(id);
    }

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/download")
    public void downloadFile(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {

        try {
            //查找mongoid 对应的数据
            DataFiles dataFiles=iDataFilesService.getByMongoId(id);
            InputStream inputStream = iDataFilesService.getFile(id);
            String fileName = dataFiles.getFileName();
            DownLoadFileUtils.downloadFile(fileName, inputStream, request, response);
        } catch (Exception e) {
            //e.printStackTrace();
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("文件不存在");
        }
    }

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/download/file")
    public void downloadFileByFileId(String fileId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        try {
            DataFiles dataFiles = iDataFilesService.getById(fileId);
            InputStream inputStream = iDataFilesService.getFile(dataFiles.getFileMongoId());
            String fileName = dataFiles.getFileName();
            DownLoadFileUtils.downloadFile(fileName, inputStream, request, response);
        } catch (Exception e) {
            //e.printStackTrace();
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("文件不存在");
        }
    }


    @ApiOperation(value = "文件预览")
    @RequestMapping(value = "/view/{id}")
    @ResponseBody
    public ResponseEntity<Object> serveFileOnline(@PathVariable String id) throws Exception {

        InputStream inputStream = iDataFilesService.getFile(id);
        DataFiles dataFiles = iDataFilesService.getByMongoId(id);
        if (dataFiles != null) {
            String name = java.net.URLEncoder.encode(dataFiles.getFileName(), "UTF-8");
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + name + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, dataFiles.getFileType())
                    .header(HttpHeaders.CONTENT_LENGTH, dataFiles.getFileSize() + "").header("Connection", "close")
                    .body(new InputStreamResource(inputStream));
        } else {

            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }

    @ApiOperation(value = "文件预览")
    @RequestMapping(value = "/view/file")
    public ResponseEntity<Object> serveFileOnlineByFileID(String fileId) throws Exception {
        DataFiles dataFiles = iDataFilesService.getById(fileId);
        InputStream inputStream = iDataFilesService.getFile(dataFiles.getFileMongoId());
        String name = java.net.URLEncoder.encode(dataFiles.getFileName(), "UTF-8");
        byte[] content = IOUtils.toByteArray(inputStream);
        try {
            inputStream.close();
        }catch (Exception e)
        {
            e.getMessage();
        }
        if (dataFiles.getIsDel() == 0) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + name + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, dataFiles.getFileType())
                    .header(HttpHeaders.CONTENT_LENGTH, dataFiles.getFileSize() + "").header("Connection", "close")
                    .body(new ByteArrayResource(content));
        } else {

            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }

    @ApiOperation(value = "文件删除")
    @RequestMapping(value = "/deleteByFileId")
    @ResponseBody
    public CommonResult deleteByFileID(String fileId) throws Exception {
        DataFiles dataFiles = iDataFilesService.getById(fileId);
        dataFiles.setIsDel(1);
        iDataFilesService.updateById(dataFiles);
        boolean isdelete = gridFSRepository.delete(dataFiles.getFileMongoId());
        return CommonResult.success(isdelete);

    }

    /**
     * 上传到服务器
     *
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/uploadLocal")
    public CommonResult uploadLocal(@RequestParam(value = "file", required = false) MultipartFile file,String enterpriseName) {
        String result =  iDataFilesService.uploadLocal(file,enterpriseName);
        videoLocalService.inset(enterpriseName,result,uploadFolder,accessPrefixUrl);
        return CommonResult.success(result);
    }

}
